<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{:lang('设置套餐')}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="__CSS__/admin.css" media="all">
</head>
<style>
    .addPackage{
        float: right;
        margin-top: -4px;
    }
    .fastSpec{
        margin-top: 4px;
    }
    .fastSpec:first-child{
        margin-left: 10px;
    }
    #roomSkuTable .layui-input{
        width: 100px;
    }
    .delAttr,.delAttrValue{
        font-size: 20px;color: #ff5722;
    }
    .attrValueDIV{
        background-color: #eee;padding: 0 8px;
    }
    .addNewAttrValue{
        margin-top: 10px;
    }
</style>
<body>
<div class="layui-container" style="padding: 15px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <blockquote class="layui-elem-quote">
                <span>设置房间SKU</span>
            </blockquote>
            <form class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">选择规格</label>
                    <div class="layui-input-inline">
                        <select name="spec" class="layui-select" lay-filter="selectSpec">
                            <option value="">请选择规格</option>
                            {notempty name='$specs'}{volist name='specs' id='vo'}
                            <option value="{$vo.id}" data-json="{$vo.attr_json}">{$vo.spec_name}</option>
                            {/volist}{/notempty}
                        </select>
                    </div>
                    <div class="layui-input-inline" style="margin-top: 4px;">
                        <a class="layui-btn layui-btn-sm addHotelSpuSpec"  style="margin-left: 10px;">添加新规格</a>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">关联属性</label>
                    <div class="layui-input-inline" style="width:89%">
                        <blockquote class="layui-elem-quote elem-quote-div" id="attrValuesDIV" style="width: 80%">

                        </blockquote>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-inline" style="width:100%">
                        批量设置 :
                    <table class="layui-table" id="batchSetInput">
                        <colgroup>
                            <col width="25%">
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                            <col width="15%">
                        </colgroup>
                        <tr>
                            <th>房间编号</th>
                            <th>参考成本价</th>
                            <th>参考销售价</th>
                            <th>参考市场价</th>
                            <th>库存</th>
                            <th>操作</th>
                        </tr>
                        <tr>
                            <th><input type="text" class="layui-input" readonly name="batch_room_code" autocomplete="off"></th>
                            <th><input type="text" class="layui-input" name="batch_cost_price" autocomplete="off"></th>
                            <th><input type="text" class="layui-input" name="batch_sales_price" autocomplete="off"></th>
                            <th><input type="text" class="layui-input" name="batch_market_price" autocomplete="off"></th>
                            <th><input type="text" class="layui-input" name="batch_stock" autocomplete="off"></th>
                            <th>
                                <a class="batchInput" style="color:#01AAED">批量添加</a> | <a class="clearBatchInput" style="color:#01AAED">清空</a>
                            </th>
                        </tr>
                    </table>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-inline" style="width:100%">
                        房间属性 :
                        <table class="layui-table" id="roomSkuTable">

                        </table>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-inline">
                        <button class="layui-btn" lay-submit lay-filter="admin">{:lang('提交')}</button>
                        <button type="reset" class="layui-btn layui-btn-primary">{:lang('重置')}</button>
                    </div>
                </div>
            </form>

        </div>
    </div>

</div>
</body>
<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>
<script>
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form;

        //提交表单
        form.on('submit(admin)', function(data) {
            var hotel_id = {$details.hotel_id}; //产品ID
            var room_skus = [];
            //组装规格数据
            var spec_id = $('select[name=spec]').val();
            var attr_json = '';
            $.each(specs_json,function (i,v) {
                if(v.id==parseInt(spec_id)){
                    attr_json = v.attr_json;
                }
            })
            //组装价格数据
            var trs = $("#roomSkuTable tr:not(:first)");
            console.log(trs);
            var isStop = false;
            $.each(trs,function (i,v) {
                var attr_ids = [];
                $(v).find('.attr_value_sku').each(function (ii,vv) {
                    attr_ids.push($(vv).attr('data-id'));
                })
                var room_code = $(v).find('input[name=room_code]').val();
                var cost_price = $(v).find('input[name=cost_price]').val();
                var sales_price = $(v).find('input[name=sales_price]').val();
                var market_price = $(v).find('input[name=market_price]').val();
                var stock = $(v).find('input[name=stock]').val();
                if(room_code=='' || room_code==undefined){isStop=true;layer.msg('请补充所有的房间编号！');return false;}
                if(cost_price=='' || cost_price==undefined){isStop=true;layer.msg('请补充所有的成本价！');return false;}
                if(sales_price=='' || sales_price==undefined){isStop=true;layer.msg('请补充所有的销售价！');return false;}
                if(market_price=='' || market_price==undefined){isStop=true;layer.msg('请补充所有的市场价！');return false;}
                if(stock=='' || stock==undefined){isStop=true;layer.msg('请补充所有的库存！');return false;}
                room_skus.push({
                    room_code:room_code
                    ,cost_price:cost_price
                    ,sales_price:sales_price
                    ,market_price:market_price
                    ,stock:stock
                    ,attr_ids:attr_ids
                })
            })
            if(isStop){return false;}
            var post_data = {
                hotel_id:hotel_id,
                spec_id:spec_id,
                attr_json:attr_json,
                room_skus:room_skus
            }
            var loading = layer.load(2);
            $.post("",post_data,function (res) {
                layer.close(loading);
                layer.msg(res.msg);
                if(res.code > 0){
                    setTimeout(function(){
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.layer.close(index); //再执行关闭
                    },1500)
                }
            })
            return false;
        })
        var specs_json = {$specs|json_encode};
        var attr_json = '';
        form.on('select(selectSpec)',function (data) {
            var id = data.value;
            $.each(specs_json,function (i,v) {
                if(v.id==parseInt(id)){
                    attr_json = v.attr_json;
                }
            })
            var attr_arr = JSON.parse(attr_json);
            console.log(attr_arr)
            renderAttrValuesDIV(attr_arr)
            renderRoomSkuTable(attr_arr);
        })

        function renderAttrValuesDIV(attr_arr)
        {
            $("#attrValuesDIV").children().remove();
            $.each(attr_arr,function (i,v) {
                renderSelectedAttrValues(v.id,v.name,v.sub);
            })
        }

        function renderSelectedAttrValues(attr_id,attr_name,datas){
            //检查是否重复设置
            $('#attrValuesDIV .attrID').each(function (i,v) {
                if($(v).attr('data-id')==attr_id){
                    $(v).parent().parent().remove();return false;
                }
            })
            var html = '<div class="layui-card">' +
                '<div class="layui-card-header">' +
                '<div class="layui-inline attrID" data-id="'+ attr_id +'">'+ attr_name +'</div>' +
                '<i class="layui-icon delAttr">&#x1006;</i>' +
                '</div>' +
                '<div class="layui-card-body">';
            $.each(datas,function (i,v) {
                html += '<div class="layui-inline attrValueDIV">' +
                    '<div class="layui-inline attrValueID" data-id="'+ v.id+'">' + v.name+ '</div>' +
                    '<i class="layui-icon delAttrValue" >&#x1006;</i>' +
                    '</div>';
            })

            html += '</div>' +
                '</div>';
            $('#attrValuesDIV').append(html);
        }

        function reduceTwoArr(source1,source2) {
            var res = [];
            $.each(source1,function (i,v) {
                $.each(source2,function (ii,vv) {
                    res.push(v.toString() + ',' +  vv.toString())
                })
            })
            return res;
        }

        function reduceMultipleArr(arr = []) {
            return arr.reduce((acc,currentItem) => {
                return reduceTwoArr(acc,currentItem)
            })
        }

        function renderRoomSkuTable(attr_arr)
        {
            var roomSku = [];
            var header_fields = ['房间编号','参考成本价','参考销售价','参考市场价','库存','操作'];
            $.each(attr_arr,function (i,v) {
                header_fields.unshift(v.name);
                var attr_value_ids = [];
                $.each(v.sub,function (ii,vv) {
                    attr_value_ids.push(vv.id.toString() + '--' + vv.name)
                })
                roomSku.push(attr_value_ids)
            })
            var roomList = reduceMultipleArr(roomSku);
            console.log(roomList);
            var html = "<tr>";
            console.log(header_fields);
            $.each(header_fields,function (i,v) {
                html += '<th>'+v+'</th>';
            })
            html += "</tr>";
            $.each(roomList,function (i,v) {
                var attrValues = v.split(',');
                //console.log(v,attrValues);

                html += '<tr>';
                $.each(attrValues,function (ii,vv) {
                    var attr_value = vv.split('--');
                    //console.log(attr_value);
                    var attr_id = attr_value[0];
                    var attr_name = attr_value[1];
                    html += '<td class="attr_value_sku" data-id="'+attr_id+'">'+attr_name+'</td>';
                })
                html += '<td class="room_code"><input type="text" name="room_code" class="layui-input" autocomplete="off"></td>';
                html += '<td class="cost_price"><input type="text" name="cost_price" class="layui-input" autocomplete="off"></td>';
                html += '<td class="sales_price"><input type="text" name="sales_price" class="layui-input" autocomplete="off"></td>';
                html += '<td class="market_price"><input type="text" name="market_price" class="layui-input" autocomplete="off"></td>';
                html += '<td class="stock"><input type="text" name="stock" class="layui-input" autocomplete="off"></td>';
                html += '<td class="operate"><a class="delRoomSku" style="color:#01AAED">删除</a></td>';
                html += '</tr>';
            })
            $("#roomSkuTable").children().remove();
            $("#roomSkuTable").append(html);
        }

        $('.addHotelSpuSpec').click(function () {
            layer.open({
                title:'添加新规格',
                type:2,
                scrollBar:false,
                content:"{:url('admin/hotel/addNewHotelSpec')}",
                area:['100%','100%'],
                end:function () {
                    window.location.reload();
                }
            })
        })

        $(document).on('click','.delAttr',function () {
            var attr_id = $(this).prev().attr('data-id');
            //查找并删除当前的数据
            var id = $('select[name=spec]').val();
            var specs_index = -1;
            $.each(specs_json,function (i,v) {
                if(v.id==parseInt(id)){
                    attr_json = v.attr_json;
                    specs_index = i;
                }
            })
            var attr_arr = JSON.parse(attr_json);
            if(attr_arr.length ==1){
                layer.msg('至少保留一个属性值');return false;
            }
            $.each(attr_arr,function (i,v) {
                if(v.id==attr_id){
                    attr_arr.splice(i,1);
                    return false;
                }
            })
            //还原数据
            specs_json[specs_index]['attr_json'] = JSON.stringify(attr_arr);
            //重新渲染数据
            renderRoomSkuTable(attr_arr);
            $(this).parent().parent().remove();
        })
        $(document).on('click','.delAttrValue',function () {
            var attr_value_id = $(this).prev().attr('data-id');
            //查找并删除当前的数据
            var id = $('select[name=spec]').val()
            var specs_index = -1;
            $.each(specs_json,function (i,v) {
                if(v.id==parseInt(id)){
                    attr_json = v.attr_json;
                    specs_index = i;
                }
            })
            var attr_arr = JSON.parse(attr_json);
            var isStop = false;
            $.each(attr_arr,function (i,v) {
                console.log(attr_arr,attr_value_id)
                if(v.sub.length ==1){
                    isStop = true;
                    layer.msg('至少保留一个属性值和属性可选值');return false;
                }
                $.each(v.sub,function (ii,vv) {
                    if(vv.id==attr_value_id){
                        attr_arr[i]['sub'].splice(i,1);
                        return false;
                    }
                })
            })
            if(isStop){return false;}
            //还原数据
            specs_json[specs_index]['attr_json'] = JSON.stringify(attr_arr);
            //重新渲染数据
            renderRoomSkuTable(attr_arr);
            $(this).parent().remove();
        })

        //批量设置
        $('.batchInput').click(function(){
            if($("#batchSetInput input").length > 0){
                $("#batchSetInput input").each(function (i,v) {
                    if($(v).attr('name')=='batch_cost_price' && $(v).val()!==''){
                        $('#roomSkuTable input[name=cost_price]').val($(v).val());
                    }
                    if($(v).attr('name')=='batch_sales_price' && $(v).val()!==''){
                        $('#roomSkuTable input[name=sales_price]').val($(v).val());
                    }
                    if($(v).attr('name')=='batch_market_price' && $(v).val()!==''){
                        $('#roomSkuTable input[name=market_price]').val($(v).val());
                    }
                    if($(v).attr('name')=='batch_stock' && $(v).val()!==''){
                        $('#roomSkuTable input[name=stock]').val($(v).val());
                    }
                    if($(v).attr('name')=='batch_room_code'){
                        $('#roomSkuTable input[name=room_code]').each(function (ii,vv) {
                            $(vv).val(getBatchRoomCode($(v).val(),ii));
                        });
                    }
                })
            }
        })
        $('.clearBatchInput').click(function(){
            $("#batchSetInput input").not("[name=batch_room_code]").val('');
        })

        function getBatchRoomCode(time,index)
        {
            var arr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            var year_index = (new Date).getFullYear() - 2020;
            var year = arr[year_index];
            var rand_index = index % 26;
            time = (time=='' || time==undefined) ? (new Date()).getTime() : parseInt(time);
            //时间戳减去20200901
            return 'H' + year + (time - (new Date('2020-09-01')).getTime()).toString(36).toUpperCase() + arr[rand_index] + index;
        }

        $('#batchSetInput input[name=batch_room_code]').val((new Date).getTime())

        $(document).on('click','.delRoomSku',function () {
            $(this).parent().parent().remove();
        })
    });
</script>
</html>